# coding:utf8
"""

"""

import poplib
import base64
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
# Local
from e_mail.send.m_iniRead import format_file as ff

mailQQ = '../send/_sup/info_qqEmail.ini'


def get_email_content():
    print('Begin eMail')
    _info = ff(mailQQ)
    userAccount = _info['mailUser']
    password = _info['mailPasswd']
    pop3_server = 'pop.qq.com'  # 邮件服务器地址,以下为网易邮箱

    server = poplib.POP3(pop3_server)  # 创建POP3实例
    server.set_debuglevel(1)  # 打开或者关闭调试信息，为打开，会在控制台打印客户端与服务器的交互信息
    # print(server.getwelcome().decode('utf8'))  # 打印POP3服务器的欢迎文字，验证是否正确连接到了邮件服务器

    # 开始进行身份验证
    server.user(userAccount)
    server.pass_(password)

    email_num, email_size = server.stat()  # 返回邮件总数目和占用服务器的空间大小（字节数）， 通过stat()方法即可
    # print("消息的数量: {0}, 消息的总大小: {1}".format(email_num, email_size))

    # 使用list()返回所有邮件的编号，默认为字节类型的串
    rsp, msg_list, rsp_siz = server.list()
    # print("服务器的响应: {0},\n消息列表： {1},\n返回消息的大小： {2}".format(rsp, msg_list, rsp_siz))

    # print('邮件总数： {}'.format(len(msg_list)))

    total_mail_numbers = len(msg_list)  # 下面单纯获取最新的一封邮件
    rsp, msglines, msgsiz = server.retr(total_mail_numbers)
    # print("服务器的响应: {0},\n原始邮件内容： {1},\n该封邮件所占字节大小： {2}".format(rsp, msglines, msgsiz))

    msg_content = b'\r\n'.join(msglines).decode('gbk')

    msg = Parser().parsestr(text=msg_content)
    # print('解码后的邮件信息:\n{}'.format(msg))

    server.close()  # 关闭与服务器的连接，释放资源
    return msg


def parser_subject(msg):
    subject = msg['Subject']
    value, charset = decode_header(subject)[0]
    if charset:
        value = value.decode(charset)
    print('邮件主题： {0}'.format(value))
    return value


def parser_content(msg):
    content = msg.get_payload()

    print(content[0])

    # 文本信息
    content_charset = content[0].get_content_charset()  # 获取编码格式
    text = content[0].as_string().split('base64')[-1]
    # print(type(text))
    # print(type(base64.b64decode(text)))
    # text_content = text.decode(content_charset)
    text_content = base64.b64decode(text).decode(content_charset)  # base64解码

    # 添加了HTML代码的信息
    content_charset = content[1].get_content_charset()
    text = content[1].as_string().split('base64')[-1]
    html_content = base64.b64decode(text).decode(content_charset)
    print('文本信息: {0}\n添加了HTML代码的信息: {1}'.format(text_content, html_content))
    return text_content, html_content


def main():
    msg = get_email_content()
    title = parser_subject(msg)
    massage = parser_content(msg)
    for m in massage:  open(f'./_sup/{m[2]}.txt', 'w').write(m)
    return 0


if __name__ == '__main__':
    main()
